/**
 * Chargement des données JSON pour l'affichage du graphe Highcharts DeltaPM.
 */
function loadGraphWaterfall(nivGeog, geog, idGeog) {
	var quota = "";
	if ($('#quotaRadioMarcheId').get(0).checked) {
		quota = "QM";
	} else if ($('#quotaRadioProduitId').get(0).checked) {
		quota = "QP";
	}
	var product    = $('#productId').get(0).value;
	var source = $('#sourceId').get(0).value;
	var periode = $('#periodId').get(0).value;
	var unite = $('#unitId').get(0).value;
	
	if (statutProduit == 'complet' || statutProduit == 'pasDeMarche') {
		$.ajax({
	 		traditional: true, 
	 		type: 'POST', 
	 		url: './dataWaterfall.do',
	 		target: "_blank", 
	 		data : {
	 			nivGeog: 	nivGeog,
				geog: 		geog,
				source: 	source,
				product:	product,
				idGeog: 	idGeog,
				periode: 	periode,
				unite:		unite,
				quota:		quota
	 		},
	 		error: function () {},
	 		success: function(result) { 
	 			displayGraphWaterfall(result, nivGeog, geog); 
	 		}
	 	}); 
	} else {
		$('#graphWaterfall').html('<div align="center" style="padding-top:50px;" class="text-general">Non applicable pour ce produit</div>');
	}
}

/**
 * Affichage du graphe Highcharts Waterfall.
 */
function displayGraphWaterfall(json, nivGeog, geog) {
	
	var clickDetected = false;
	
	var bal = $('#periodId').get(0).options[$('#periodId').get(0).selectedIndex].text;
	
	var min = 1000000;
	var max = -1000000;
	var tmp = 0;
	var i = 0;
	for (val in json.data1) {
		if (i == 0) {
			tmp = json.data1[val].y;
			min = json.data1[val].y;
			max = json.data1[val].y;
		} else {
			tmp += json.data1[val].y;
			min = Math.min(min, tmp);
			max = Math.max(max, tmp);
		}
		i++;
	}
	
	// Ajout de la balance 
	var balance = new Object();
	balance.name = bal;
	balance.isSum = true;
	balance.color = '#1143d8';
	json.data1.push(balance);
	
	var firstColLabel = "";
	
	// Affichage du titre du graphe
	var title = "";
	if (nivGeog == geog) { // Niveau France
		title = nivGeog;
	} else { // Autres niveaux 
		title = geog; //nivGeog + ' ' + geog;
	}
	
	chart = new Highcharts.Chart({
		chart: {
			renderTo: 'graphWaterfall',
			type: 'waterfall'
        },
        title: {
            text: '<span style="font-size:13px;font-family:Arial;">Contribution geog : ' + lib_marche + ' : ' + title + ' (' + lib_mois + ')' + "</span>",
            useHTML: true
        },
        subtitle: {
        	text: '<span style="font-size:10px;font-family:Arial;"><b>Source :</b> ' + ' ' + $('#sourceId').get(0).options[$('#sourceId').get(0).selectedIndex].text + ' - <b>P&eacute;riode :</b> ' + $('#periodId').get(0).options[$('#periodId').get(0).selectedIndex].text + ' - <b>Indicateur produit :</b> ' + 'EVOL VOL (%)' + '</span>',
            useHTML: true
        },
        credits: {
            enabled: false
        },
        exporting: {
            enabled: true
        },
        xAxis: {
            type: 'category',
            labels: {
                rotation: 0,
                align: 'center',
                format: '{value}',
                useHTML: true,
                formatter: function() {
                	if (this.isFirst) {
                		firstColLabel = this.value + '<br />' + bal;
                		return firstColLabel + ' -1'; 
                	} else if (this.isLast) {
                		return firstColLabel;
                	} else {
                		return this.value;
                	}
                },
                style: {
                	fontSize: '9px',
                	fontFamily: 'Arial'
                }
            }		
        },
        yAxis: 
        [
	         {
	            title: {
	            	text: '<span style="font-size:11px;font-family:Arial;font-weight:normal;">' + title + '</span>',
	                useHTML: true,
	                style: {
	                    color: '#59626B'
	                }
	            },
	            min: min,
	            max: max,
	            labels: {
	                format: '{value} k', // les labels de gauche
	                formatter: function () {
	                	if (this.value >= 1000 || this.value <= -1000) {
	                		return (this.value / 1000) + 'k';
	                	} else {
	                		return this.valueOf();
	                	}
	                },
	                style: {
	                    color: '#59626B',
	                    fontSize: '9px',
	                	fontFamily: 'Arial'
	                }
	            }
	        }
        ],
        legend: {
            enabled: false
        },
        tooltip: {
            pointFormat: '<b>{point.y:,.2f}</b>'
        },
        series: [
	        {
	            upColor: Highcharts.getOptions().colors[2],
	            color: Highcharts.getOptions().colors[3],
	            data: json.data1, 
	            
	            point: {
					events: {
						click: function(event) {
		                    if (clickDetected) {
		                        // Double clic sur le graphe  
		                    	if (this.niveau != undefined ){//&& this.niveau != 'UGA') {
		                    		globalNivGeog = this.niveau;
		                        	globalGeog = this.category;
		                        	idGeog = this.idGeog;
		                        	// Ouverture de l arbre de gauche
		      		  				$(this).jstree("open_node", $("#" + idGeog + "-" + globalNivGeog).parent().parent().parent().children("a"));
		      		  				$("#" + idGeog + "-" + globalNivGeog).addClass("jstree-clicked");
		    	  		  			$("#" + idGeog + "-" + globalNivGeog).click();
		                    	}
		                        clickDetected = false;
		                    } else {
		                        clickDetected = true;
		                        setTimeout(function() {
		                            clickDetected = false;
		                        }, 500); 
		                    }
		                }
		            }
				},
				
	            dataLabels: {
	                enabled: true,
	                useHTML: true,
	                y:-22, 
	                verticalAlign: 'top',
	                formatter: function () {
	                	// Pourcentage
	                	var pourcentage = "";
	                	if (this.x == 0) { // premier x
	                		pourcentage = "";
	                	} else if (this.series.data[this.x].pourcent != undefined) {
	                		pourcentage = "(" + this.series.data[this.x].pourcent + "%)";
	                	} else { // dernier x
	                		pourcentage = "(" + this.series.data[0].pourcent + "%)"; // on se sert du premier pourcentage 
	                	}
	                	if (this.y >= 1000 || this.y <= -1000) {
	                		var tmp = this.y /1000;
	                		return '<span style="font-size:9px;">' + tmp.toFixed(1) + 'k' + ' ' + pourcentage + '</span>';
	                	} else {
	                		return '<span style="font-size:9px;">' + this.y + ' ' + pourcentage  + '</span>';
	                	}
	                },
	                style: {
	                    color: '#0000FF'
	                }
	            },
	            pointPadding: 0
	        }
        ]
    });
	
}